//
//  44.翻转单词序列.swift
//  数据结构与算法
//
//  Created by ZERO on 2021/5/27.
//

import Foundation
/*
 题目：牛客最近来了一个新员工Fish，每天早晨总是会拿着一本英文杂志，写些句子在本子上。同事Cat对Fish写的内容颇感兴趣，有一天他向Fish借来翻看，但却读不懂它的意思。例如，“nowcoder. a am I”。后来才意识到，这家伙原来把句子单词的顺序翻转了，正确的句子应该是“I am a nowcoder.”。Cat对一一的翻转这些单词顺序可不在行，你能帮助他么？
 思路1：API
 思路2：空格截断保存
 */
func offer_44() {
    print(Solution().ReverseSentence2("nowcoder. a am I"))
}

fileprivate class Solution {
    func ReverseSentence1(_ ReverseSentence: String) -> String {
        return ReverseSentence.components(separatedBy: " ").reversed().joined(separator: " ")
    }
    
    func ReverseSentence2(_ ReverseSentence: String) -> String {
        var i = 0
        let sz = ReverseSentence.count
        for c in ReverseSentence {
            if c == " " {
                i += 1
            }
        }
        guard i != sz else { return ReverseSentence }
        
        var result = ""
        var temp = ""
        var hasStr = false
        for c in ReverseSentence {
            if c != " " {
                temp += String(c)
                hasStr = true
            } else if c == " " && hasStr {
                result = " " + temp + result
                temp = ""
                hasStr = false
            }
        }
        if temp != "" {
            result = temp + result
        }
        return result
    }
}
